package com.hanyxx.thread.lock;

import lombok.SneakyThrows;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author layman
 * @date 2021/2/9
 */
public class Demo07 {
    public static void main(String[] args) {
        Demo07Service service = new Demo07Service();
        Demo07ThreadA t1 = new Demo07ThreadA(service);
        Demo07ThreadB t3 = new Demo07ThreadB(service);
        Demo07ThreadB t4 = new Demo07ThreadB(service);
        t1.setName("读线程01");
        t3.setName("写线程01");
        t4.setName("写线程02");
        t1.start();
        t3.start();
        //t4.start();
    }
}
class Demo07Service{
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() throws InterruptedException {
        lock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+" 获得读锁于："+System.currentTimeMillis());
        Thread.sleep(1000L);
        System.out.println(Thread.currentThread().getName()+" 释放读锁于："+System.currentTimeMillis());
        lock.readLock().unlock();
    }
    public void write() throws InterruptedException {
        lock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+" 获得写锁于："+System.currentTimeMillis());
        Thread.sleep(1000L);
        System.out.println(Thread.currentThread().getName()+" 释放写锁于："+System.currentTimeMillis());
        lock.writeLock().unlock();
    }
}
class Demo07ThreadA extends Thread{
    private Demo07Service service;
    public Demo07ThreadA(Demo07Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.read();
    }
}
class Demo07ThreadB extends Thread{
    private Demo07Service service;
    public Demo07ThreadB(Demo07Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.write();
    }
}
